package br.com.wai2008.socket.position;

import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import br.com.wai2008.socket.client.SocketClient;
import br.com.wai2008.socket.constants.SocketClientConstants;

/**
 * This class implements a call to the position estimation service. It calls it
 * through socket, because the service was developed using C++ language.<br>
 * To execute the position estimation service, we need to give three informations:
 * the HD serial number for a device, the access points IDs and the wireless signals.<br>
 * This service returns to us the estimated x and y position for this device.
 * 
 * @since 
 * 		September, 2008.
 * 
 * @version
 * 		WAI2008 - version 1.0
 * 
 * @author 
 * 		Andre Romero Goncales
 */
public class PositionEstimation {

	/**
	 * Get the estimated position for the device.<br>
	 * To get this position, we must connect to the service through socket. So,
	 * be sure the client's server, port and timeout is correctly setted.
	 *  
	 * @see 
	 * 		br.com.wai2008.socket.protocol.ServerToServerProtocol
	 * @see
	 * 		br.com.wai2008.socket.constants.SocketClientConstants
	 * 
	 * @param
	 * 		ccProtocol message to be sent to the estimation position service.
	 * 		This message must be in a ServerToServerProtocol and must contain the 
	 * 		access points IDS and its signals and the HD serial number for the device.
	 * 
	 * @return
	 * 		The message received from the Estimated Position's Server.
	 */
	public String getPosition(String ccProtocol) {
		System.out.println("[PositionEstimation] Getting position...");
		try {
			if (ccProtocol != null) {
				SocketClient socketClient = new SocketClient(SocketClientConstants.CLIENT_HOST, 
								SocketClientConstants.CLIENT_PORT, SocketClientConstants.REQUEST_TIMEOUT);
				socketClient.startConnection();
				socketClient.sendMessage(ccProtocol);
				String serverResponse = socketClient.receiveMessage();
				return serverResponse;
			} else {
				System.out.println("[PositionEstimation] ERROR: Input message null");
				return null;
			}
		} catch (UnknownHostException e) {
			System.out.println("[PositionEstimation] ERROR: Server not found");
			e.printStackTrace();
		} catch (SocketTimeoutException e) { 
			System.out.println("[PositionEstimation] ERROR: Timeout while waiting response message");
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("[PositionEstimation] ERROR: Failed to send message");
			e.printStackTrace();
		} 
		return null;
	}	
}
